<!-- ProductItem.vue -->
<script setup>
import {onBeforeUnmount, reactive, ref} from "vue";
import "animate.css"
import { ElMessage, ElMessageBox } from 'element-plus'
import customDialogVue from "@/views/customDialogVue.vue"
import {Comment, Delete, InfoFilled, Position} from "@element-plus/icons-vue";
import {deleteCommentService, getCommentService, sendCommentService} from "@/api/comments.js";
import {useTokenStore} from "@/stores/token.js";
import {useUserIdStore} from "@/stores/userInfo.js";
import {useRoute, useRouter} from "vue-router";
import {useDefaultAvatarStore} from "@/stores/defaultAvatar.js";
import {incrementLookedNumService} from "@/api/goods.js";
import {saveUserBehaviorService} from "@/api/userBehavior.js";
const props = defineProps({
  goods: Object,
  onShowDetails: Function // 新增显示详情的回调函数属性
})
const goods = ref(props.goods);

// 用户行为
const userBehavior = reactive({
  goodsId: goods.value.id,
  behaviorType:null,
  commentText:null,
  pageViewDuration:null,
});


const route = useRouter();

const description = ref();
const modifyDescription = () => {
  // if (goods.value.description.length > 25) {
  //   return goods.value.description.substring(0, 25) + "......";
  // } else {
  //   return goods.value.description;
  // }
  return goods.value.description;
};

//图片点击放大
const isImgClicked = ref(false)

const showPopover = ref([]) // 是否显示弹出框

const tokenStore = useTokenStore();
const userIdStore = useUserIdStore();
description.value = modifyDescription();
const dialogTableVisible = ref(false);

const startTimestamp = ref();
const endTimestamp = ref();
const timestamp = ref(); //浏览页面市场，单位/秒

const openDialog = () => {
  //打开dialog时获取评论
  getComments();
  if (tokenStore.token === ""){
    return;
  }
  dialogTableVisible.value = true;
  startTimestamp.value = new Date().getTime();

  incrementLookedNumService(goods.value.id); // 增加浏览量

  props.onShowDetails && props.onShowDetails(goods);
}
const closeDialog = () => {
  dialogTableVisible.value = false;
  endTimestamp.value = new Date().getTime();
  timestamp.value = (endTimestamp.value - startTimestamp.value) / 1000;
  console.log("浏览页面时间：" + timestamp.value + "秒")
  userBehavior.pageViewDuration = Math.round(timestamp.value);
  userBehavior.behaviorType = 0;
  userBehavior.commentText = null;
  saveUserBehaviorService(userBehavior);
}

const dialogTitle = ref("");
dialogTitle.value = goods.value.qualityName+" "+goods.value.goodsName;

const pushTime = ref();
const getPushTime = ()=>{

  if (goods.value.updateTime !== goods.value.createTime) {
    pushTime.value = `更新时间 ${goods.value.updateTime}・IP 属地 ${goods.value.ipTerritory}`;
  } else {
    pushTime.value = `发布时间 ${goods.value.createTime}・IP 属地 ${goods.value.ipTerritory}`;
  }
}
getPushTime();
const sendButton = ref(false);
const showSendButton = () => {
  sendButton.value = true;
}
const closeSendButton = () => {
    sendButton.value = false;
}

//发送评论参数
const commentData = ref({
  goodsId: goods.value.id,
  content: ""
})

const defaultAvatarStore = useDefaultAvatarStore();
//默认头像
const defaultPic = ref(defaultAvatarStore.defaultAvatar)

//获取到评论对象数组
const comments = ref([])

//获取评论
const getComments = async () => {
  let result = await getCommentService(goods.value.id, goods.value.userId)
  comments.value = result.data
}
const initShowPopover = () => {
  for (let i = 0; i < comments.value.length; i++){
    showPopover.value[i] = false;
  }
}
initShowPopover();

//发送评论
const sendComment = async () =>{
  if (commentData.value.content.length === 0){
    ElMessage({
      message: '评论内容不能为空',
      type: 'error',
      customClass: 'global-messageZindex'
    })
    return;
  }
  let result = await sendCommentService(commentData.value)
  if (result.code === 0){
    userBehavior.behaviorType = 2;
    userBehavior.commentText = commentData.value.content;
    saveUserBehaviorService(userBehavior); // 保存用户行为
    sendButton.value = false;
    commentData.value.content = "";
    await getComments();
    ElMessage({
      message: '评论成功',
      type: 'success',
      customClass: 'global-messageZindex'
    })
  }
}
const deleteComments = async (commentsId)=>{
  await deleteCommentService(commentsId);
  await getComments();
  ElMessage({
          type: 'success',
          message: '删除成功',
          customClass: 'global-messageZindex'
        })
}

const contactSeller = (userId)=>{
  if (userIdStore.userId === userId){
    ElMessage({
      type: 'error',
      message: '不能联系自己哦',
      customClass: 'global-messageZindex'
    })
    return;
  }
  route.push(`/messageCenter?contactUserId=${userId}`)
}

const handleKeyDown = (event) =>{
  if (!dialogTableVisible.value) return;
  if (event.key === 'Escape'){
    event.stopPropagation();
    event.preventDefault();
    if (isImgClicked.value === true){
      isImgClicked.value = false;
    }else{
      closeDialog();
    }
  }
  if (event.key === 'Enter'){
    event.stopPropagation();
    event.preventDefault();
    if (sendButton.value === true){
      sendComment();
    }
  }
}
window.addEventListener('keydown', handleKeyDown);
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown);
})
</script>

<template>
  <div class="content">
    <div class="product-item animate__animated animate__zoomIn" @click="openDialog">
      <img :src="goods.pic" alt="Product Image" class="product-image"/>
      <div class="seller-info">
        <span class="seller-name"><b>卖家:</b> {{ goods.username }}</span><br>
        <span class="seller-item" style="white-space: nowrap"><b>商品:</b> {{ goods.goodsName }}</span><br>
        <span class="seller-quality"><b>成色:</b> {{ goods.qualityName }}</span><br>
        <span class="seller-price"><b>价格:</b> <span style="color: red">{{ goods.price }} 元</span></span><br>
        <span class="seller-description"><b>描述: </b>{{ description }}</span>
      </div>
    </div>
    <div v-if="dialogTableVisible" class="dialog">
      <customDialogVue
          v-if="dialogTableVisible"
          :visible="dialogTableVisible"
          @close="closeDialog();closeSendButton()" >
        <template v-slot:header>
          {{ dialogTitle }}
        </template>
        <template v-slot:body>
          <div class="sell-content" @click="closeSendButton()">
            <img :src="goods.pic" alt="Product Image" class="product-image" @click="isImgClicked = true"/>
            <div v-if="isImgClicked" class="big-img-container" @click.self="isImgClicked = false">
              <img
                  :src="goods.pic"
                  alt="Product Image"
                  class="big-img animate__animated animate__zoomIn animate__faster"
              >
            </div>
            <div class="seller-info">
              <span class="seller-name"><b>卖家:</b> {{ goods.username }}<button class="contact-button" @click="contactSeller(goods.userId)">联系他</button></span><br>
              <span class="seller-name"><b>手机号/微信:</b> {{ goods.phone }}</span><br>
              <span class="seller-name"><b>QQ号:</b> {{ goods.qqNumber }}</span><br>
              <span class="seller-item"><b>商品:</b> {{ goods.goodsName }}</span><br>
              <span class="seller-quality"><b>成色:</b> {{ goods.qualityName }}</span><br>
              <span class="seller-price"><b>价格:</b> <span style="color: red">{{ goods.price }} 元</span></span><br>
              <span class="seller-description"><b>描述: </b>{{ goods.description }}</span>
              <div class="push-time">
                <span>{{pushTime}}</span>
              </div>
            </div>
          </div>
          <!-- 新增评论区 -->
          <div class="comments-section">
            <div class="add-comment-form">
              <input v-model="commentData.content" placeholder="写下你的评论..." class="content-input" @click="showSendButton()">
              <div v-if="sendButton" class="animate__animated animate__slideInDown animate__faster comment-send">
                <p>注意：评论内容仅供交流，禁止发布违法信息</p>
                <button @click="sendComment()">发布</button>
              </div>
            </div>
          </div>
          <div class="comment-list" @click="closeSendButton()">
            <el-row v-if="comments.length !== 0" v-for="(comment,index) in comments" :key="comment.id" class="comment-item">
              <el-col :span="24">
                <el-row>
                  <el-col :span="1">
                    <div class="popovers" @mouseenter="showPopover[index] = true" @mouseleave="showPopover[index] = false">
                      <el-avatar shape="square"
                                 :size="50" :fit="'fill'"
                                 :src="comment.userPic===null||comment.userPic.length===0?defaultPic : comment.userPic" />
                      <div class="popover" v-if="showPopover[index]">
                        <button @click="contactSeller(comment.userId)">发送消息</button>
                        <button>查看主页</button>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="23">
                    <div class="comment-content">
                      <span class="comment-username">{{ comment.userName }}</span>
                      <el-tag v-if="comment.seller" type="primary" class="seller-tag">卖家</el-tag>
                      <el-tag v-if="comment.selfOne && !comment.seller" type="info" class="self-tag">本人</el-tag>
                      <el-icon v-if="comment.selfOne" ><el-button class="delete-comment-button" @click="deleteComments(comment.id)"><Delete/></el-button></el-icon>
                      <span class="comment-time">{{ comment.createTime }}</span><br/>
                      <span class="comment-content">{{ comment.content }}</span>
                    </div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row v-else>
              <el-col :span="24">
                <span style="color: #999999;font-size: 20px;margin-top: 20px;margin-bottom: 20px;padding: 8px">暂无评论...</span>
              </el-col>
            </el-row>
          </div>
        </template>
      </customDialogVue>
    </div>
  </div>
</template>


<style lang="scss" scoped>
 .content{
   .product-item {
     /* 设置商品容器的样式，比如宽高比、内边距等 */
     width: 250px;
     height: 420px;
     display: flex;
     flex-direction: column;
     align-items: center;
     background-color: #fafafa;
     border: 1px solid #ccc; /* 添加边框样式，此处以灰色为例 */
     border-radius: 6px;
     transition: all 0.3s ease;
     position: relative;
     overflow: hidden;
     &:hover {
       transform: scale(1.03);
       box-shadow:
           5px  5px 10px rgba(0, 0, 0, 0.1), /* 右下 */
           -5px  5px 10px rgba(0, 0, 0, 0.1), /* 左下 */
           5px -5px 10px rgba(0, 0, 0, 0.1), /* 右上（已存在，保留不变） */
           -5px -5px 10px rgba(0, 0, 0, 0.1); /* 左上 */
     }

     .product-image {
       /* 设置商品图片的样式 */
       width: 90%;
       height: 65%;
       background-size: contain;
       margin-top: 10px;
       border-radius: 10px;
     }

     .seller-info {
       width: 90%;
       white-space: nowrap;
       overflow: hidden;
       text-overflow: ellipsis;
       user-select: none;
       position: absolute;
       justify-content: flex-start;
       /* 卖家信息样式 */
       text-align: left;
       top: 70%;
       left: 10px;;
       span {
         width: 100%;
         font-size: 15px;
         color: #2c2b2b;
         font-family: "华文新魏", serif;
       }

       b {
         color: black;
       }
     }
   }
   /* 对话框样式*/
   .sell-content{
     width: 100%;
     display: flex;
     height: 470px;
     max-height: 470px;
     border-bottom: 1px solid #ccc;
     .product-image{
       margin-top: 10px;
       width: 25%;
       height: 450px;
       max-height: 450px;
       border-radius: 10px;
       cursor: pointer;
       border:1px solid #e0e0e0;
       &:hover{
         box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); /* 可按需调整参数 */
         transform: scale(1.01);
         transition: all 0.3s ease;;
       }
     }
     .big-img-container{
       position: fixed;
       top: 0;
       left: 0;
       right: 0;
       bottom: 0;
       display: flex;
       justify-content: center;
       align-items: center;
       z-index: 9999;
       background: rgba(0, 0, 0, 0.5);
       .big-img{
         width: 35%;
         height: 95%;
         background-size: contain;
         border-radius: 10px;
         &:hover{
           cursor: grab;
         }
       }
     }
     .contact-button{
       width: 80px;
       height: 25px;
       margin-left: 30px;
       border: none;
       cursor: pointer;
       background-color: #f3f3f3;
       border-radius: 10px;
       color: #49CD88;;
       &:hover{
         background-color: rgba(0, 0, 0, 0.1);
       }
     }
     .seller-info{
       width: 75%;
       margin-top: 10px;
       margin-left: 20px;
       max-height: 449px;
       position: relative;
       span{
         line-height: 40px;
         color: #2c2424;
         b{
           color: black;
         }
       }
       .push-time{
         position: absolute;
         right: 10px;
         bottom: 0;
         span{
           color: #858383;
         }
       }
     }
   }
   .comments-section{
     width: 100%;
     display: flex;
     justify-content: center;
     flex-direction: row;
     margin-top: 15px;
     .add-comment-form {
       .content-input{
         width: 500px;
         height: 41px;
         padding: 0 10px;
         outline-color: #55a1e0;
         border-radius: 6px;
         border: 1px solid #ccc;
       }
       .comment-send{
         position: relative;
         width: 100%;
         height: 40px;
         border-bottom: 1px solid #ccc;
         button{
           width: 100px;
           height: 30px;
           position: absolute;
           background-color: #1a8ff1;
           border: none;
           color: white;
           cursor: pointer;
           border-radius: 5px;
           right: 0;
           bottom: 2px;
           &:hover {
             background-color: darken(#90c4f3, 10%); // 示例:hover时的背景色
           }
         }
         p{
           position: absolute;
           color: #858383;
           font-size: 13px;
           left: 10px;
           top: 5px;
         }
       }
     }
   }
   .comment-list{
     margin-top: 24px;
     width: 100%;
     border: 2px solid #ccc;
     border-radius: 8px;
     min-height: 48px;
     margin-bottom: 30px;
     .comment-item{
       width: 100%;
       padding: 16px;
       .comment-content{
         margin-left: 24px;
         position: relative;
         .comment-username{
           font-size: 18px;
           font-weight: bold;
         }
         .comment-time{
           position: absolute;
            color: #858383;
           left: 400px;
         }
         .comment-content{
           margin-left: 0;
           line-height: 32px;
           color: black;
         }
       }
       .popovers{
         &:hover{
           cursor: pointer;
         }
       }
       .popover{
         position: absolute;
         border-radius: 10px;
         padding: 0 10px;
         left: -1%;
         display: flex;
         flex-direction: column;
         background-color: #fff;
         border: 1px solid #ccc;
         box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
         /* 你可以根据需要添加箭头样式 */
         z-index: 1000;
         button{
           margin-top: 10px;
           border: none;
           color: #131313;
           &:hover{
             background-color: rgba(0, 0, 0, 0.1);
             color: #00c74b;
             cursor: pointer;
           }
           border-radius: 4px;
         }
         :last-child{
            margin-bottom: 10px;
         }
       }
     }
   }
 }
.seller-tag{
  margin-left: 25px;
  height: 24px;
  background-color: white;
}
.self-tag{
  margin-left: 25px;
  height: 24px;
  background-color: white;
}
.delete-comment-button{
  border: none;
  background-color: white;
  width: 8px;
  margin-left: 50px;
  height: 23px;
  font-size: 14px;
  text-align: center;
  &:hover{
    color: red;
  }
}
 .dialog{
   position: fixed;
   top: 0;
   right:0;
   bottom: 0;
   left: 0;
   width: 100%;
   height: 100%;
   display: flex;
   justify-content: center;
   align-items: center;
   background-color: rgba(0, 0, 0, 0.5);
   z-index: 9999;
 }
</style>